<?php


namespace app\cms\community\lib\saas;

use iflow\exception\Adapter\HttpException;

class saasAccount
{

    public array $account = [];
    public array $envConfig = [];

    /**
     * 主系统 获取指定saas服务
     * @param bool $isReload 是否重新加载数据
     * @throws \Exception
     * @return array
     */
    public function getSaasAccount(bool $isReload = false): array
    {
        $host = request() -> getDomain();
        $this->getEnvConfig();

        if ($this->account && !$isReload) return $this->account;

        // 验证当前请求是否为主服务
        if ($host === $this->envConfig['application']['domain']) {
            $account = array_merge($this->envConfig['database'], $this->account);
            $account = array_merge($this->envConfig['application'], $account);
            $this->account = $account ?: [];
        } else {
            // 远程获取 租户信息 并验证
            $params = [
                'domain' => $host,
                'client_name' => $this->envConfig['saasAccountValidServer']['server_name'],
                'event' => 3
            ];

            // PHP-CLI模式 需开启SWOOLE扩展
            go(function () use (&$accountInfo, $host, $params) {
                $params['client_name'] = $params['server_name'];
                $accountInfo = rpc(
                    $this->envConfig['saasAccountValidServer']['server_ip'],
                    $this->envConfig['saasAccountValidServer']['server_port'],
                    'rpc/saas/account/valid_account',
                    $this->envConfig['saasAccountValidServer']['ssl'],
                    $params
                ) -> getData();
            });
            $account = is_array($accountInfo) ? $accountInfo : json_decode($accountInfo, true);
            if (!is_array($account) || !$account['db_ip']) throw new HttpException(402, 'SAAS服务不存在');
            $this->account = (array) $account;
        }
        if (!$this->account) return [];
        return $this->account;
    }

    public function getEnvConfig(): array
    {
        if ($this->envConfig) return $this->envConfig;
        $envPath = app() -> getRootPath() . '.env';
        if (!file_exists($envPath)) {
            return $this->envConfig;
        }
        $this->envConfig = parse_ini_file(app() -> getRootPath() . '.env', true, INI_SCANNER_TYPED);
        return $this->envConfig;
    }
}